import requests
import json
import os


def stream_audio_to_text(audio_path, server_url="http://localhost:6000/speech-to-text"):
    """
    流式发送音频文件到 speech-to-text 接口并处理实时转录结果
    """
    try:
        # 检查音频文件是否存在
        if not os.path.exists(audio_path):
            print(f"错误: 音频文件 {audio_path} 不存在")
            return

        # 打开音频文件
        with open(audio_path, 'rb') as audio_file:
            # 设置流式请求的 headers
            headers = {'Content-Type': 'audio/wav'}

            # 发送 POST 请求，流式上传音频
            with requests.post(server_url, data=audio_file, headers=headers, stream=False) as response:
                if response.status_code != 200:
                    print(f"错误: 服务器返回状态码 {response.status_code}")
                    return

                # 处理 SSE 响应
                for line in response.iter_lines():
                    if line:
                        decoded_line = line.decode('utf-8')
                        # 检查是否是 SSE 数据行
                        if decoded_line.startswith('data:'):
                            data = decoded_line[5:].strip()
                            try:
                                # 尝试解析 JSON 数据（最终结果）
                                json_data = json.loads(data)
                                if json_data.get('status') == 'success':
                                    print(f"最终转录结果: {json_data.get('text')}")
                                elif json_data.get('status') == 'error':
                                    print(f"错误: {json_data.get('message')}")
                            except json.JSONDecodeError:
                                # 非 JSON 数据，视为部分转录结果
                                print(f"部分转录结果: {data}")

    except Exception as e:
        print(f"客户端错误: {str(e)}")


if __name__ == '__main__':
    audio_file_path = "/home/weiqiangren/Python/project/py-basic-exercises/TTS/output_zh.wav"
    stream_audio_to_text(audio_file_path)